# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# 建立者:        博智科技  
# Name:         gui_demo
# Description:
# Author:       yzl
# Date:         2019-04-07
#-------------------------------------------------------------------------------


import sys
import multiprocessing

#
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import time


class Frame_main(QMainWindow):

    def __init__(self, parent = None):
        super(Frame_main, self).__init__(parent)
        self.thrd_list=[]
        self.initUI()

    def initUI(self):

        # Button
        btn_run = QPushButton('Run', self)
        btn_run.clicked.connect(lambda: self.ThdSomething(self.DoRun) ) #
        btn_stop = QPushButton('Stop', self)
        btn_stop.clicked.connect(self.DoStop)


        ### TEXT Edit
        self.textEdit_term = QTextEdit("terminal: \n ")
        self.textEdit_term.append("")
        self.textEdit_term.setStyleSheet("color: rgb(255, 255, 255); background-color: black;")
        self.textEdit_term.setLineWrapMode(QTextEdit.NoWrap)
        self.textEdit_term.setToolTip(' terminal message ')
        self.textEdit_term.setStatusTip('textEdit1')

        ### LAYOUT
        Wid_main = QWidget()                    #
        grid_major = QGridLayout()              #
        grid_major.addWidget( btn_run, 1, 5)
        grid_major.addWidget( btn_stop, 2, 5)
        Wid_main.setLayout(grid_major)

        self.setCentralWidget(Wid_main)

        ### Affichage
        self.show()                 #

    #
    def DoRun(self):
        print('g starts')
        time_start=time.time()
        time_stop=time.time()
        name='bob'
        n=0
        while time_stop-time_start <2 :
            n+=1
            time_stop=time.time()
            time.sleep(0.8)
            print ('hola', name,n, flush=True)
        print('g stops')

    def DoStop(self):
        ''' subourtine kill all the thread '''
        print('stop action detected')
        while len(self.thrd_list) > 0 :
            print("Terminating the job: {}".format(self.thrd[-1].pid) )
            os.kill(self.thrd[-1].pid, signal.SIGTERM)
            self.thrd_list[-1].terminate()

            self.thrd_list.pop()


    def ThdSomething(self, job):
        ''' subourtine to create a new thread to do the job subroutine '''
        arg=''
        p=multiprocessing.Process(target=job, args=(arg))
        self.thrd_list.append( p )
        p.start()
        # print("Start the job GUI: {} with PID: {}".format(str(job) ,self.thrd[-1].pid), file=sys.stdout )


    def closeEvent(self, event):
        ''' subroutine to define what happen when closing the main frame'''
        self.statusBar().showMessage('waiting for a respond')
        reply = QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QMessageBox.Yes |
            QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()


# Main
if __name__ == '__main__':
    # Create QApplication and Main Frame
    Qapp = QApplication(sys.argv)   # creation de lappli Qt
    Qapp.setStyle("fusion")         #
    frame1 = Frame_main()           #

    sys.exit(Qapp.exec_())          #
